<template>
  <view class="order-content py-10px px-12px">
    <view
      class="address-info px-12px py-14px rounded-2px"
      @click.stop="handleChangeAddress"
    >
      <view class="flex-1">
        <view class="flex items-center">
          <view class="address-tag">收货地址</view>
          <view
            class="ml-8px mr-5px text-default"
            :class="{ 'text-grey': !address.value.name }"
          >
            {{ address.value.name || "添加收货地址" }}</view
          >
          <view class="text-grey text-xs text-12px">{{
            address.value.phone
          }}</view>
        </view>
        <view
          v-if="address.value.detailAddress"
          class="address text-grey2 text-xs mt-10px leading-none"
        >
          {{ addressDetail(address.value) }}
        </view>
      </view>
      <image :src="ossImg('others/component/right.png')" />
    </view>
    <view class="order-info my-base py-18px px-9px rounded-2px">
      <view
        class="order-goods flex items-start mb-24px"
        v-for="item in info.items"
        :key="item.id"
      >
        <view
          class="goods-cover"
          :style="{ backgroundImage: `url(${item.productImageUrl})` }"
        >
        </view>
        <view class="pl-8px pr-22px text-base text-goods flex-1">
          {{ item.productName }}
        </view>
        <view class="flex flex-col items-end">
          <view class="text-primary whitespace-nowrap leading-none mb-10px">
            ¥ {{ item.productSkuPrice }}
            <!--          <text class="text-12px">00</text>-->
          </view>
          <view class="text-14px text-grey">x{{ item.quantity }}</view>
        </view>
      </view>
      <!-- <view class="order-info__line">
        购买数量：
        <stepper v-model:value="form.quantity" />
      </view> -->

      <view class="order-info__line">
        订单备注：
        <input
          v-model="form.note"
          placeholder="选填，可填写特殊需求等"
          placeholder-style="color: #BCBCBC"
        />
      </view>
      <view class="flex justify-end mt-28px">
        <view class="text-base flex items-center">
          <view class="text-grey">共{{ info.items.length || 0 }}件</view>
          <view class="flex items-center">
            <view class="ml-10px">小计：</view>
            <view class="text-primary">¥{{ info.totalPrice || 0 }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="order-coupon rounded-2px" @click.stop="visible = true">
      <view>优惠券：</view>
      <view class="text-primary flex items-center">
        <view class="coupon">{{ coupon }}</view>
        <image :src="ossImg('others/component/arrow.png')" />
      </view>
    </view>

    <view class="order-info px-12px pt-25px pb-20.5px">
      <view class="flex items-center items-start justify-between text-base">
        <view class="flex items-center"
          >配送方式：<view class="text-desc">快递配送</view>
        </view>
        <view v-if="address.value.detailAddress">
          <span v-if="info.freightPrice === 0">包邮</span>
          <span v-else>{{ `¥${info.freightPrice || 0}` }}</span>
          <!-- <span v-else>
            <span v-if="info.freightDiscounted" class="price_line-through">{{
              `¥${info.defaultFreight || 0}`
            }}</span>
            <span class="text-primary">
              {{ `¥${info.freightPrice || 0}` }}</span
            >
          </span> -->
        </view>
      </view>

      <!-- <view class="order-info__freightPrice mt-13px">
        {{
          `订单优惠后金额满${info.freightDiscountThreshold}元减免${info.freightDiscount}元运费`
        }}<span v-if="!info.freightDiscounted"
          >，还差<span style="color: #f43148"
            >{{
              Math.abs(cal.jian(info.finalPrice, info.freightDiscountThreshold))
            }} </span
          >元</span
        >
      </view> -->
    </view>

    <view
      class="order-ad my-base"
      :style="{ backgroundImage: `url(${ossImg('personal/hd_banner.png')})` }"
      @click.stop="toWebView"
    ></view>
    <view class="agree" v-if="!info.privacyPolicyAgreed">
      <view class="flex items-center">
        <template>
          <image
            v-if="iAgree"
            class="i-agree"
            :src="ossImg('register/checkbox.png')"
            @click.stop="iAgree = false"
          />
          <view v-else class="i-agree" @click.stop="iAgree = true"> </view>
        </template>
        <view class="agree-content">
          同意凯诘收集订单信息以供处理及交付您所订购的货物。详情见
          <view class="link" @click="linkTo('/pages/PrivacyPolicy2/index')"
            >《凯诘隐私政策》 </view
          >和<view class="link" @click="linkTo('/pages/SalesEntityInfo/index')"
            >《销售主体资质信息》</view
          >
        </view>
      </view>
    </view>
  </view>
  <view class="order-submit">
    <view class="flex items-center order-total text-grey">
      合计：<view class="submit-price text-primary price"
        >{{
          info.totalPrice - coupon + info.freightPrice > 0
            ? cal.jia(cal.jian(info.totalPrice, coupon), info.freightPrice)
            : 0
        }}
      </view>
    </view>
    <button
      class="bg-primary"
      v-if="info.totalPrice - coupon > 0"
      @click.stop="onCreateOrder"
    >
      提交订单
    </button>
    <button class="bg-primary" v-else @click.stop="requestSubscribe">
      提交订单
    </button>
  </view>

  <!-- 优惠
  券选择列表 -->
  <oreo-popup :show="visible" round position="bottom">
    <order-coupon-list
      :couponHistories="info.couponHistories"
      :unusableCouponHistories="info.unusableCouponHistories"
      :couponId="form.couponId"
      :title="'优惠券'"
      @close="onCloseCoupon"
    />
  </oreo-popup>


</template>

<script setup>
import { ossImg } from "@/utils/utils";
import Stepper from "@/components/stepper.vue";
import OrderCouponList from "@/components/order-coupon-list.vue";
import { reactive, ref } from "vue";
import { CreateOrder, wxOrderPurchase } from "@/services/mall";
import { Subscribe } from "@/services/utils";
import { GetCartSettle } from "@/services/cart";
import { onShow, onUnload, onHide, onLoad } from "@dcloudio/uni-app";
import { message, generateSign, randomString, debounce } from "@/utils/utils";
import { cal } from "@/utils/cal";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const visible = ref(false);
const address = reactive({
  value: {
    name: "",
    phone: "",
  },
});
const coupon = ref(0);
const info = ref({
  items: [],
});
const form = reactive({
  quantity: 1,
  addressId: "",
  couponId: "",
  productSkuId: "",
  note: "",
});
const iAgree = ref(false);
const toPage = ref("");
const currentCoupon = ref({});

onLoad((option) => {
  // getAddressList();
  console.log(option);
  if (option.productSkuId) {
    toPage.value = "goods";
    form.quantity = parseInt(option.quantity);
    form.productSkuId = option.productSkuId;
  } else {
    toPage.value = "cart";
    if (option.couponId) {
      form.couponId = option.couponId;
    }
  }
  console.log(toPage.value);
  getInfo(option);
});

onShow(async () => {
  // 用户进入时间
  enterTime = new Date();
  // choose address callback
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage.data.hasOwnProperty("addressInfo")) {
    address.value = currentPage.data.addressInfo;
    form.addressId = currentPage.data.addressId;
    console.log(address.value, form);
  }
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;

  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    "order_submit_page",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "view",
    "order_submit_page",
    stayTime
  );
});

const requestSubscribe = () => {
  if (form.addressId === undefined || form.addressId === "")
    return message("地址不能为空！");
  if (!iAgree.value && !info.value.privacyPolicyAgreed)
    return message("请先同意相关协议!");
  uni.requestSubscribeMessage({
    tmplIds: [process.env.ORDERDELIVERYNOTICE],
    success: async (res2) => {
      // 订阅成功
      onCreateOrder();
    },
    fail: function (err) {
      console.log(err);
    },
  });
};

const onCreateOrder = debounce(
  async () => {
    // create order
    if (form.addressId === undefined || form.addressId === "")
      return message("地址不能为空！");
    if (!iAgree.value) return message("请先同意相关协议!");
    const { addressId, couponId, note, productSkuId, quantity } = form;

    if (toPage.value === "goods") {
      // 快速购买
      const res = await CreateOrder({
        appId: process.env.WXAPPID,
        addressId,
        couponId,
        note: note === "" ? null : note,
        productSkuId,
        quantity,
      });
      if (res?.code === 200) {
        getApp().emdlz2(
          "track",
          "event",
          "store_page",
          "click",
          `order_create_${res.data}_${info.id},${productSkuId}`,
          `${
            info.value.totalPrice - coupon.value + info.value.freightPrice > 0
              ? info.value.totalPrice - coupon.value + info.value.freightPrice
              : 0
          }`
        );
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: res.data,
              order_time: Date.now(),
              order_status: "give_order",
            },
            sub_orders: [
              {
                sub_order_id: res.data,
                order_amt: info.value.totalPrice,
                pay_amt:
                  info.value.totalPrice -
                    coupon.value +
                    info.value.freightPrice >
                  0
                    ? info.value.totalPrice -
                      coupon.value +
                      info.value.freightPrice
                    : 0,
              },
            ],
            // more...
          });
        if (
          info.value.totalPrice - coupon.value + info.value.freightPrice >
          0
        ) {
          orderPurchase(res.data);
        } else {
          getApp()
            .sr()
            .track("consume_coupon", {
              action_type: "consume",
              coupon: {
                coupon_id: currentCoupon.value.id,
                coupon_name: currentCoupon.value.name,
              },
              coupon_batch: {
                coupon_batch_id: currentCoupon.value.id,
                coupon_batch_name: currentCoupon.value.name,
              },
              // more...
            });
          getApp()
            .sr()
            .track("custom_order", {
              order: {
                order_id: res.data,
                order_time: Date.now(),
                order_status: "pay",
              },
              sub_orders: [
                {
                  sub_order_id: res.data,
                  order_amt: info.value.totalPrice,
                  pay_amt:
                    info.value.totalPrice -
                      coupon.value +
                      info.value.freightPrice >
                    0
                      ? info.value.totalPrice -
                        coupon.value +
                        info.value.freightPrice
                      : 0,
                },
              ],
              // more...
            });

          console.log(1123132, uni.getLaunchOptionsSync());

          await Subscribe({
            appId: process.env.WXAPPID,
            orderId: res.data,
            scene: ["ORDER_DELIVERY"],
          });

          const body = {
            wxScene: uni.getLaunchOptionsSync().scene,
            scene: uni.getLaunchOptionsSync().query.scene
              ? uni.getLaunchOptionsSync().query.scene
              : uni.getStorageSync("SCENE") || "",
            type: "order",
            orderId: res.data,
            channelId: "",
            nonce: randomString(),
            timestamp: parseInt(new Date().getTime() / 1000),
          };

          uni.request({
            url: `${process.env.BASE_API}s-mall/api/access-log/loginaccess`,
            method: "post",
            data: {
              ...body,
              ...{ sign: generateSign(body) },
            },
            header: {
              Authorization: uni.getStorageSync("TOKEN")
                ? `Bearer ${uni.getStorageSync("TOKEN")}`
                : "",
            },
          });

          // await accessLogAdd({ ...body, ...{ sign: generateSign(body) } });

          message("支付成功", 1000);
          uni.reLaunch({
            url: "/pages/paySuccess/index",
          });
        }
      } else {
        message(res.message, 2500);
      }
    } else if (toPage.value === "cart") {
      // 非快速购买
      const res = await CreateOrder({
        appId: process.env.WXAPPID,
        addressId,
        couponId,
        note: note === "" ? null : note,
      });
      console.log(res);
      if (res?.code === 200) {
        if (
          info.value.totalPrice - coupon.value + info.value.freightPrice >
          0
        ) {
          orderPurchase(res.data);
        } else {
          console.log(
            22222,
            info.value.totalPrice - coupon.value + info.value.freightPrice
          );

          getApp()
            .sr()
            .track("consume_coupon", {
              action_type: "consume",
              coupon: {
                coupon_id: currentCoupon.value.id,
                coupon_name: currentCoupon.value.name,
              },
              coupon_batch: {
                coupon_batch_id: currentCoupon.value.id,
                coupon_batch_name: currentCoupon.value.name,
              },
              // more...
            });
          getApp()
            .sr()
            .track("custom_order", {
              order: {
                order_id: res.data,
                order_time: Date.now(),
                order_status: "pay",
              },
              sub_orders: [
                {
                  sub_order_id: res.data,
                  order_amt: info.value.totalPrice,
                  pay_amt:
                    info.value.totalPrice -
                      coupon.value +
                      info.value.freightPrice >
                    0
                      ? info.value.totalPrice -
                        coupon.value +
                        info.value.freightPrice
                      : 0,
                },
              ],
              // more...
            });

          await Subscribe({
            appId: process.env.WXAPPID,
            orderId: res.data,
            scene: ["ORDER_DELIVERY"],
          });

          const body = {
            wxScene: uni.getLaunchOptionsSync().scene,
            scene: uni.getLaunchOptionsSync().query.scene
              ? uni.getLaunchOptionsSync().query.scene
              : uni.getStorageSync("SCENE") || "",
            type: "order",
            orderId: res.data,
            channelId: "",
            nonce: randomString(),
            timestamp: parseInt(new Date().getTime() / 1000),
          };

          uni.request({
            url: `${process.env.BASE_API}s-mall/api/access-log/loginaccess`,
            method: "post",
            data: {
              ...body,
              ...{ sign: generateSign(body) },
            },
            header: {
              Authorization: uni.getStorageSync("TOKEN")
                ? `Bearer ${uni.getStorageSync("TOKEN")}`
                : "",
            },
          });

          // await accessLogAdd({ ...body, ...{ sign: generateSign(body) } });

          message("支付成功", 1000);
          uni.reLaunch({
            url: "/pages/paySuccess/index",
          });
        }
      } else {
        message(res.message, 2500);
      }
    }
  },
  500,
  false
);

const orderPurchase = async (id) => {
  getApp()
    .sr()
    .track("custom_order", {
      order: {
        order_id: id,
        order_time: Date.now(),
        order_status: "pay",
      },
      sub_orders: [
        {
          sub_order_id: id,
          order_amt: info.value.totalPrice,
          pay_amt:
            info.value.totalPrice - coupon.value + info.value.freightPrice > 0
              ? info.value.totalPrice - coupon.value + info.value.freightPrice
              : 0,
        },
      ],
      // more...
    });

  const res = await wxOrderPurchase({ id, appId: process.env.WXAPPID });
  if (res?.code === 200) {
    uni.requestPayment({
      provider: "wxpay", //支付类型-固定值
      timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
      nonceStr: res.data.nonceStr, // 随机字符串
      package: res.data.package, // 固定值
      signType: res.data.signType, //固定值
      paySign: res.data.paySign, //签名
      success: async function (res) {
        console.log("success:" + JSON.stringify(res));

        getApp().emdlz2(
          "track",
          "event",
          "store_page",
          "click",
          `pay_success_${id}`,
          `${
            info.value.totalPrice - coupon.value + info.value.freightPrice >= 0
              ? info.value.totalPrice - coupon.value + info.value.freightPrice
              : 0
          }`
        );
        getApp()
          .sr()
          .track("consume_coupon", {
            action_type: "consume",
            coupon: {
              coupon_id: currentCoupon.value.id,
              coupon_name: currentCoupon.value.name,
            },
            coupon_batch: {
              coupon_batch_id: currentCoupon.value.id,
              coupon_batch_name: currentCoupon.value.name,
            },
            // more...
          });

        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: id,
              order_time: Date.now(),
              order_status: "payed",
            },
            sub_orders: [
              {
                sub_order_id: id,
                order_amt: info.value.totalPrice,
                pay_amt:
                  info.value.totalPrice -
                    coupon.value +
                    info.value.freightPrice >
                  0
                    ? info.value.totalPrice -
                      coupon.value +
                      info.value.freightPrice
                    : 0,
              },
            ],
            // more...
          });

        console.log(1123132, uni.getLaunchOptionsSync());

        message("支付成功", 1000);
        uni.requestSubscribeMessage({
          tmplIds: [process.env.ORDERDELIVERYNOTICE],
          success: async (res2) => {
            console.log(res2);
            await Subscribe({
              appId: process.env.WXAPPID,
              orderId: id,
              scene: ["ORDER_DELIVERY"],
            });
            // 订阅成功
            uni.reLaunch({
              url: "/pages/paySuccess/index",
            });
          },
          fail: function (err) {
            console.log(err);
          },
        });
        const body = {
          wxScene: uni.getLaunchOptionsSync().scene,
          scene: uni.getLaunchOptionsSync().query.scene
            ? uni.getLaunchOptionsSync().query.scene
            : uni.getStorageSync("SCENE") || "",
          channelId: "",
          type: "order",
          orderId: id,
          nonce: randomString(),
          timestamp: parseInt(new Date().getTime() / 1000),
        };

        uni.request({
          url: `${process.env.BASE_API}s-mall/api/access-log/loginaccess`,
          method: "post",
          data: {
            ...body,
            ...{ sign: generateSign(body) },
          },
          header: {
            Authorization: uni.getStorageSync("TOKEN")
              ? `Bearer ${uni.getStorageSync("TOKEN")}`
              : "",
          },
        });

        // await accessLogAdd({ ...body, ...{ sign: generateSign(body) } });
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));
        getApp()
          .sr()
          .track("custom_order", {
            order: {
              order_id: id,
              order_time: Date.now(),
              order_status: "cancel_pay",
            },
            sub_orders: [
              {
                sub_order_id: id,
                order_amt: info.value.totalPrice,
                pay_amt:
                  info.value.totalPrice -
                    coupon.value +
                    info.value.freightPrice >
                  0
                    ? info.value.totalPrice -
                      coupon.value +
                      info.value.freightPrice
                    : 0,
              },
            ],
            // more...
          });

        uni.showModal({
          title: "确定取消支付吗？",
          content: "120分钟内未付款，订单将自动关闭，请尽快付款哦！",
          cancelText: "稍后付款",
          confirmText: "继续付款",
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
              orderPurchase(id);
            } else if (res.cancel) {
              console.log("用户点击取消");
              message("取消支付");
              uni.redirectTo({ url: "/personalPages/order/detail?id=" + id });
            }
          },
        });
      },
    });
  } else {
    message(res.message, 2500);
  }
};

const handleChangeAddress = () => {
  uni.navigateTo({
    url: "/pages/address/address?choose=1",
  });
};

const toWebView = () => {
  getApp().emdlz2(
    "track",
    "event",
    "store_page",
    "click",
    "order_confirm_page_banner",
    ""
  );

  linkTo(
    "/pages/webView/webview?webSrc=https://mp.weixin.qq.com/s/T6ThaRY-yimSkm0b2pH2Tg"
  );
};

const linkTo = (url) => uni.navigateTo({ url });

const addressDetail = ({ province, city, region, detailAddress }) => {
  return province + city + region + detailAddress;
};

const getInfo = async (body) => {
  const res = await GetCartSettle({ ...body });
  if (res?.code === 200) {
    info.value = res.data;
    iAgree.value = res.data.privacyPolicyAgreed;

    if (toPage.value === "goods") {
      form.couponId = info.value.couponId;
      info.value.couponHistories.find((item) =>
        item.id === form.couponId
          ? ((coupon.value = item.off), (currentCoupon.value = item))
          : null
      );
    } else if (toPage.value === "cart") {
      info.value.couponHistories.find((item) =>
        item.id === form.couponId
          ? ((coupon.value = item.off), (currentCoupon.value = item))
          : null
      );
    }
  } else {
    message(res.message, 2500);
  }

  form.productSkuId = info.value.items
    .map((obj, index) => {
      return obj.productSkuId;
    })
    .join(",");
  if (!res.data.addresses || !res.data.addresses.length) return;
  const defaultAddress = res.data.addresses.find((item) => item.defaultFlag);
  console.log(defaultAddress);
  if (defaultAddress) {
    address.value = defaultAddress;
    form.addressId = defaultAddress.id;
  }
};

const onCloseCoupon = (val) => {
  visible.value = false;

  if (val.id) {
    form.couponId = val.id;
    coupon.value = val.off;
    currentCoupon.value = val;
    // if (toPage.value === "goods") {
    //   getInfo({
    //     couponId: form.couponId,
    //     productSkuId: form.productSkuId,
    //     quantity: form.quantity,
    //   });
    // } else if (toPage.value === "cart") {
    //   getInfo({ couponId: form.couponId });
    // }
  } else {
    coupon.value = 0;
    form.couponId = "";
  }
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";
@submit-height: 52px;

.order-content {
  padding-bottom: @submit-height;
}

.order-info {
  background-color: white;

  .order-goods {
    .goods-cover {
      width: 68px;
      min-width: 68px;
      height: 68px;
      border-radius: 4px;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
  }

  .order-info__line {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 27px;
    color: #353535;
    font-size: 14px;
    line-height: 1;

    input {
      text-align: right;
      flex: 1;
    }
  }

  .order-info__freightPrice {
    font-size: 10px;
    color: #999999;
    text-align: right;
  }

  .price_line-through {
    text-decoration: line-through;
    color: #bcbcbc;
    font-size: 10px;
    margin-right: 5px;
  }
}

.address-info {
  background-color: white;
  display: flex;
  align-items: center;

  .address-tag {
    width: 58px;
    height: 22px;
    line-height: 22px;
    background: #e8f0fb;
    color: #0058c6;
    font-size: 12px;
    text-align: center;
  }

  image {
    width: 5px;
    height: 10px;
  }
}

.order-coupon {
  width: 100%;
  box-sizing: border-box;
  height: 60px;
  background-color: white;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #353535;

  image {
    display: block;
    width: 7px;
    height: 10px;
    margin-left: 12px;
  }

  .coupon {
    position: relative;
    font-size: 16px;

    text {
      font-size: 14px;
    }

    &::before {
      content: "-¥";
      font-size: 12px;
    }
  }
}

.order-ad {
  width: 100%;
  height: 160px;
  background-color: rgba(0, 0, 0, 0.4);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

.order-submit {
  width: 100%;
  height: @submit-height;
  background: white;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 0 14px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;

  button {
    color: white;
    width: 100px;
    height: 40px;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 20px;
    margin: 0;
    padding: 0;
    font-size: 16px;
    font-weight: normal;
    letter-spacing: 1px;

    &::after {
      border: none;
    }
  }

  .order-total {
    font-size: 14px;
  }

  .submit-price {
    font-size: 16px;
    font-weight: bold;
  }
}

.agree {
  font-size: 12px;
  color: #777777;
  padding: 0 12px 12px 12px;
  box-sizing: border-box;
  z-index: 10;

  .agree-content {
    word-break: break-all;
  }

  .link {
    color: #222222;
    display: inline-block;
    font-weight: bold;
    text-decoration: underline;
  }

  image.i-agree {
    background-color: @primary-color;
  }

  .i-agree {
    width: 16px;
    min-width: 16px;
    height: 16px;
    margin-right: 16px;
    border: 2px solid @primary-color;
    box-sizing: border-box;
  }
}
</style>
